package cate.game.role.friend;

import cate.common.table.d.GDFriend;
import cate.common.util.GameResult;
import cate.game.role.Role;
import cate.game.role.RoleDependent;
import cate.game.role.friend.msg.FriendApplyRecvResp;
import cate.game.role.friend.msg.FriendApplyRemoveResp;
import com.fasterxml.jackson.annotation.JsonIgnore;
import cp.solution.util.collection.ListKit;
import easy.java.dev.note.NoteClass;
import easy.java.dev.note.NoteField;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;

import java.util.*;

@NoteClass(value = "添加好友的申请列表")
public class FriendApply extends RoleDependent {
    @NoteField(value = "申请列表")
    public List<FriendApplyItem> items;

    @Override
    public void initialize(Role role) {
        super.initialize(role);
        if (items == null) {
            items = new ArrayList<>();
        } else {
            items = ListKit.trimMaxKeepTail(items, GDFriend.APPLY_KEEP_MAX);
        }
    }

    /**
     *
     * @param item 申请信息
     */
    public GameResult<Void> recv(FriendApplyItem item) {
        GameResult<Void> r = new GameResult<>();
        Iterator<FriendApplyItem> iterator = items.iterator();
        boolean removeSame = false;
        while (iterator.hasNext()) {
            FriendApplyItem old = iterator.next();
            if (old == null) {
                logger.error("FriendApplyPO.recv空对象之 old == null");
                iterator.remove();
                continue;
            } else if (old.applicant == null) {
                logger.error("FriendApplyPO.recv空对象之 old.applicant == null");
                iterator.remove();
                continue;
            } else if (old.applicant.uid == null) {
                logger.error("FriendApplyPO.recv空对象之 old.applicant_idHex == null");
                iterator.remove();
                continue;
            }
            if (item == null) {
                logger.error("FriendApplyPO.recv空对象之 item == null");
                iterator.remove();
                continue;
            } else if (item.applicant == null) {
                logger.error("FriendApplyPO.recv空对象之 item.applicant == null");
                iterator.remove();
                continue;
            } else if (item.applicant.uid == null) {
                logger.error("FriendApplyPO.recv空对象之 item.applicant._idHex == null");
                iterator.remove();
                continue;
            }
            if (StringUtils.equals(old.applicant.uid, item.applicant.uid)) {
                iterator.remove();
                removeSame = true;
            }
        }
        if (isFull()){
            items.remove(0);
        }
        items.add(item);
        if (!removeSame) {
            role.sendNow(new FriendApplyRecvResp(item));
        }
        return r;
    }

    public void removeIfFriend(String uid){
        boolean remove = items.removeIf(item -> StringUtils.equals(item.applicant.uid, uid));
        if(remove){
            List<String> list = new ArrayList<>();
            list.add(uid);
            role.sendNow(new FriendApplyRemoveResp(list));
        }
    }

    public void checkBlackList(Map<String,Friend> blackList){
        items.removeIf(tmp -> tmp == null || blackList.containsKey(tmp.applicant.uid));
    }

    public void removeSomeOne(String roleUid) {
        boolean remove = items.removeIf(e -> e == null || StringUtils.equals(e.applicant.uid, roleUid));
        if (remove) {
            role.sendNow(new FriendApplyRemoveResp(Collections.singletonList(roleUid)));
        }
    }

    @JsonIgnore
    private List<FriendApplyItem> getToDealList(String applicantIdHex){
        List<FriendApplyItem> toDeals;
        if(applicantIdHex == null){
            toDeals = new ArrayList<>(items);
        }else{
            toDeals = new ArrayList<>();
            Iterator<FriendApplyItem> iterator = items.iterator();
            while (iterator.hasNext()) {
                FriendApplyItem tmp = iterator.next();
                if (StringUtils.equals(tmp.applicant.uid, applicantIdHex)) {
                    toDeals.add(tmp);
                    break;
                }
            }
        }
        return toDeals;
    }

    /** 处理好友申请 */
    public void handleApply(String applicantIdHex, boolean ok) {
        List<FriendApplyItem> toDeals = getToDealList(applicantIdHex);
        if (CollectionUtils.isEmpty(toDeals)) {
            return;
        }
        List<String> toNotify = new ArrayList<>();
        for(FriendApplyItem toDeal : toDeals){
            try{
                if (ok) {
                    if(role.getFriend().isFull()){
                        break;
                    }
                    Friend acceptor = new Friend(role);
                    acceptor.ownerIdHex = toDeal.applicant.uid;
                    if(role.getGame().friend.canAdd(acceptor)) {
                        role.getFriend().add(toDeal.applicant);
                    }else{
                        if (StringUtils.isNotBlank(applicantIdHex)) {
                            role.getGame().notice.message(role, "对方已经将我拉进黑名单，无法添加其为好友");
                        }
                    }
                }
                items.remove(toDeal);
                toNotify.add(toDeal.applicant.uid);
            }catch(Exception e){
                logger.error("处理好友申请异常, e=", e);
            }
        }
        if(!toNotify.isEmpty()){
            if(ok){
                if(applicantIdHex == null){
                    role.getGame().notice.message(role,"一键添加成功");
                }else{
                    role.getGame().notice.message(role, "成功和" + toDeals.get(0).applicant.base.name + "成为好友");
                }
            }
            role.sendNow(new FriendApplyRemoveResp(toNotify));
        }
    }

    @JsonIgnore
    public boolean isFull(){
        return items.size() >= GDFriend.APPLY_KEEP_MAX;
    }
}
